//
//  HSYBaseViewController+Device.m
//  高仿暴走斗图
//
//  Created by key on 16/3/23.
//  Copyright © 2016年 huangsongyao. All rights reserved.
//

#import "HSYBaseViewController+Device.h"
#import "HSYBaseViewController+Alert.h"
#import "RACDelegateProxy.h"
#import "MPMediaPickerController+RACSignal.h"

@implementation HSYBaseViewController (Device)

#pragma mark - Check On System Device

- (BOOL)isCanUseCamera {
    
    return [self isCanOpenCameraDeviceForSourceType:UIImagePickerControllerSourceTypeCamera];
}

- (BOOL)isCanOpenCameraDeviceForSourceType:(UIImagePickerControllerSourceType)sourceType {
    
    return [UIImagePickerController isSourceTypeAvailable:sourceType];
}


- (BOOL)isCanOpenCameraDeviceForDeviceType:(kSystemDeviceType)deviceType {

    UIImagePickerControllerSourceType sourceType;
    switch (deviceType) {
        case kSystemAnimationTypeAudio: {
            
            return YES;
        }
            break;
            
        case kSystemAnimationTypeVideo: {
            
            sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
        }
            break;
            
        case kSystemAnimationTypePhoto: {
         
            sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        }
            break;
            
        case kSystemAnimationTypeCamera: {
            
            sourceType = UIImagePickerControllerSourceTypeCamera;
        }
            break;
            
        default:
            break;
    }
    
    return [self isCanOpenCameraDeviceForSourceType:sourceType];
}


#pragma mark - Open System Resource

- (RACSignal *)rac_openSystemResourcesForDeviceType:(kSystemDeviceType)type withCompletion:(void(^)(UIViewController *viewController))completion dismissCompletion:(void(^)())dismissCompletion {
    
    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
       
        if (type == kSystemAnimationTypeAudio) {
            
            [[[self openSystemMediaPickerControllerWithDeviceType:type withMediaPickerCompletion:completion dismissCompletion:dismissCompletion] deliverOn:[RACScheduler mainThreadScheduler]] subscribeNext:^(id x) {
                
                [subscriber sendNext:x];
                [subscriber sendCompleted];
            }];
            
        } else {
            
            [[[self openCameraDeviceForDeviceType:type withCompletion:completion dismissCompletion:dismissCompletion] deliverOn:[RACScheduler mainThreadScheduler]] subscribeNext:^(id x) {
                
                [subscriber sendNext:x];
                [subscriber sendCompleted];
            }];
        }
        return nil;
    }];
}

#pragma mark - Open Camera Device

- (RACSignal *)openCameraDeviceForDeviceType:(kSystemDeviceType)deviceType withCompletion:(void(^)(UIImagePickerController *imagePickerController))completion dismissCompletion:(void(^)())dismissCompletion {
    
    @weakify(self);
    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
        
        @strongify(self);
        [self openCameraDeviceWithDeviceType:deviceType withImagePickerCompletion:^(UIImagePickerController *imagePickerController) {
            @strongify(self);
            completion(imagePickerController);
            [[[self rac_imageSelectedSignalForImagePickerController:imagePickerController] deliverOn:[RACScheduler mainThreadScheduler]] subscribeNext:^(id x) {
                [subscriber sendNext:x];
                [subscriber sendCompleted];
            }];
        } dismissCompletion:dismissCompletion];

        return nil;
    }];
    
}


#pragma mark - MPMediaPickerController

- (MPMediaPickerController *)createMediaPickerControllerForDelegate:(id<MPMediaPickerControllerDelegate>)delegate andMediaType:(MPMediaType)mediaType withPrompt:(NSString *)prompt allowsPickingMultipleItems:(BOOL)allowsPickingMultipleItems {
    
    MPMediaPickerController *mediaPickerController = [[MPMediaPickerController alloc]initWithMediaTypes:mediaType];
    mediaPickerController.delegate = delegate;                                      //委托
    mediaPickerController.prompt = prompt;                                          //提示文字
    mediaPickerController.allowsPickingMultipleItems = allowsPickingMultipleItems;  //是否允许一次选择多个
    
    return mediaPickerController;
}

- (RACSignal *)openSystemMediaPickerControllerWithDeviceType:(kSystemDeviceType)deviceType withMediaPickerCompletion:(void(^)(MPMediaPickerController *mediaPickerController))completion dismissCompletion:(void(^)())dismissCompletion {
    
    if (![self isCanOpenCameraDeviceForDeviceType:deviceType]) {
        
        [self showAlertHUDWithText:HSYLOCALIZED(@"对不起,本设备不支持本功能")];
        return nil;
    }
    
    MPMediaPickerController *mediaPickerController = [self createMediaPickerControllerForDelegate:self
                                                                                     andMediaType:MPMediaTypeAnyAudio
                                                                                       withPrompt:@""
                                                                       allowsPickingMultipleItems:YES];
    
    completion(mediaPickerController);
    @weakify(self);
    [[[self rac_willCancelSignalForMediaPickerController:mediaPickerController] deliverOn:[RACScheduler mainThreadScheduler]] subscribeNext:^(id x) {
     
        @strongify(self);
        [self cameraDeviceDismissViewControllerForAnimated:YES completion:^{
            dismissCompletion();
        }];
    }];
    
    
    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
        
        [[[mediaPickerController rac_mediaSelectSignal] deliverOn:[RACScheduler mainThreadScheduler]] subscribeNext:^(id x) {
            
            
            [subscriber sendNext:x];
            [subscriber sendCompleted];
        }];
        return nil;
    }];
}

#pragma mark - MPMediaPickerController For RAC

- (RACSignal *)rac_willCancelSignalForMediaPickerController:(MPMediaPickerController *)mediaPickerController {
    
    if (![self checkMediaPickerController:mediaPickerController]) {
        return nil;
    }
    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
        
        [[[mediaPickerController.rac_delegateProxy signalForSelector:@selector(mediaPickerDidCancel:)] deliverOn:[RACScheduler mainThreadScheduler]] subscribeNext:^(id x) {
            [subscriber sendNext:x];
            [subscriber sendCompleted];
        }];
        return nil;
    }];
}


- (RACSignal *)rac_mediaSelectedSignalForMediaPickerController:(MPMediaPickerController *)mediaPickerController {
    
    if (![self checkMediaPickerController:mediaPickerController]) {
        return nil;
    }
    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
        
        [[[mediaPickerController rac_mediaSelectSignal] deliverOn:[RACScheduler mainThreadScheduler]] subscribeNext:^(id x) {
            [subscriber sendNext:x];
            [subscriber sendCompleted];
        }];
        return nil;
    }];
}

#pragma mark - UIImagePickerController

/**
 *  根据不同的资源类型创建不同的UIImagePickerController对象
 *
 *  @param deviceType        资源类型
 *  @param completion        创建UIImagePickerController对象后的回调
 *  @param dismissCompletion dismiss UIImagePickerController控制器完成后的block
 */
- (void)openCameraDeviceWithDeviceType:(kSystemDeviceType)deviceType withImagePickerCompletion:(void(^)(UIImagePickerController *imagePickerController))completion dismissCompletion:(void(^)())dismissCompletion {
    
    if ([self isCanOpenCameraDeviceForDeviceType:deviceType]) {
        
        UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
        imagePickerController.delegate = self;
        imagePickerController.allowsEditing = YES;//打开图片编辑，设置为NO时不会跳转到系统定义下的编辑页面
        
        switch (deviceType) {
            case kSystemAnimationTypePhoto: {
                imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                imagePickerController.mediaTypes = [[NSArray alloc] initWithObjects:(NSString *)kUTTypeImage, nil];  //过滤视频、音频,保留图片
            }
                break;
                
            case kSystemAnimationTypeCamera: {
                imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
                NSArray *temp_MediaTypes = [UIImagePickerController availableMediaTypesForSourceType:imagePickerController.sourceType];
                imagePickerController.mediaTypes = temp_MediaTypes;
            }
                break;
                
            case kSystemAnimationTypeVideo: {
                imagePickerController.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
                imagePickerController.mediaTypes = [[NSArray alloc] initWithObjects:(NSString *)kUTTypeMovie, (NSString *)kUTTypeVideo, nil];     //过滤相片,只保留视频类型
            }
                break;
                
            default:
                break;
        }
        
        if(ISIOS8) {
            self.modalPresentationStyle = UIModalPresentationPopover;
        }
        completion(imagePickerController);
        @weakify(self);
        [[self rac_willCancelSignalForImagePickerController:imagePickerController] subscribeNext:^(id x) {
            @strongify(self);
            [self cameraDeviceDismissViewControllerForAnimated:YES completion:dismissCompletion];
        }];
    } else {
        
        [self showAlertHUDWithText:HSYLOCALIZED(@"对不起,本设备不支持摄像机/相册")];
    }
}


#pragma mark - UIImagePickerController For RAC

/**
 *  rac_选中相片后的回调
 *
 *  @param imagePickerController UIImagePickerController对象
 *
 *  @return rac 的信号源
 */
- (RACSignal *)rac_imageSelectedSignalForImagePickerController:(UIImagePickerController *)imagePickerController {
    
    if (![self checkImagePickerController:imagePickerController]) {
        return nil;
    }
    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
        
        [[[imagePickerController rac_imageSelectedSignal] deliverOn:[RACScheduler mainThreadScheduler]] subscribeNext:^(id x) {
            [subscriber sendNext:x];
            [subscriber sendCompleted];
        }];
        return nil;
    }];
}

/**
 *  rac_选中取消按钮时的回调
 *
 *  @param imagePickerController UIImagePickerController对象
 *
 *  @return rac 的取消信号
 */
- (RACSignal *)rac_willCancelSignalForImagePickerController:(UIImagePickerController *)imagePickerController {
    
    if (![self checkImagePickerController:imagePickerController]) {
        return nil;
    }
    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
       
        [[[imagePickerController.rac_delegateProxy signalForSelector:@selector(imagePickerControllerDidCancel:)] deliverOn:[RACScheduler mainThreadScheduler]] subscribeNext:^(id x) {
            [subscriber sendNext:x];
            [subscriber sendCompleted];
        }];
        return nil; 
    }];
}


#pragma mark - Check Device ViewController

/**
 *  统一管理check imagePickerController 是否new了
 *
 *  @param imagePickerController imagePickerController
 *
 *  @return 布尔值，YES表示new了，NO相反
 */
- (BOOL)checkImagePickerController:(UIImagePickerController *)imagePickerController {
    
    if (imagePickerController) {
        return YES;
    }
    return NO;
}


/**
 *  统一管理check mediaPickerController 是否new了
 *
 *  @param mediaPickerController mediaPickerController
 *
 *  @return 布尔值，YES表示new了，NO相反
 */
- (BOOL)checkMediaPickerController:(MPMediaPickerController *)mediaPickerController {
    
    if (mediaPickerController) {
        return YES;
    }
    return NO;
}

#pragma mark - Dismiss ViewController

- (void)cameraDeviceDismissViewControllerForAnimated:(BOOL)animated completion:(void(^)())completion {
    
    [self dismissViewControllerAnimated:animated completion:completion];
}

@end
